package com.obas.monitor;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class SendPolicyFile implements Runnable {

   private Socket soc;
   private OutputStream _socketOut;
   private InputStream _socketIn;

   public SendPolicyFile(Socket s) throws IOException {
      this.soc = s;
      _socketOut = s.getOutputStream();
      _socketIn = s.getInputStream();
      // 设置超时的限制
//       soc.setSoTimeout(1000);
   }

   public void run() {
      try {
         readRandSp();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   private void readRandSp() throws IOException {
      if (read().equals("<policy-file-request/>")) {
         writePolicy();
      }
      // close stream and socket
      close();
   }

   // 写策略文件的方法
   private void writePolicy() throws IOException {
	  String xml = "<?xml version=\"1.0\"?><cross-domain-policy><site-control permitted-cross-domain-policies=\"all\"/><allow-access-from domain=\"*\" to-ports=\"*\"/></cross-domain-policy>\0";
      PrintWriter pw = new PrintWriter(_socketOut);
      pw.println(xml);
      pw.flush();
      pw.close();
   }

   public void close() {
      if (_socketOut != null)
         try {
            _socketOut.close();
            if (_socketIn != null)
               _socketIn.close();
            if (soc != null)
               soc.close();
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      _socketIn = null;
      _socketOut = null;
      soc = null;
   }

   private String read() throws IOException {
      StringBuffer buffer = new StringBuffer();
      int codePoint;
      boolean zeroByteRead = false;
      do {
         // 这个地方阻塞了
         codePoint = this._socketIn.read();
         if (codePoint == 0)
            zeroByteRead = true;
         else
            buffer.appendCodePoint(codePoint);
      } while (!zeroByteRead && buffer.length() < 30);
      return buffer.toString();
   }

}
